import Taro, { Component } from '@tarojs/taro'
import {ScrollView, View} from '@tarojs/components'

import './index.less'

type PageProps = {
  onSelect?: (currentSort: any) => void,
  onDismiss?: () => void,
  top: number,
  dataList: any[]
}

type PageState = {
  isShow: boolean,
  list: any[]
}
export default class GoodsSort extends Component<PageProps, PageState> {

  static defaultProps = {
    top: 90
  }

  constructor () {
    super()
    this.state = {
      isShow: false,
      list: []
    }
  }

  render () {
    const { top } = this.props
    const { isShow, list } = this.state
    return (
      isShow ? (
        <View className='container' onTouchMove={this._handleEvent}>
          <View className='masker' onClick={this.dismiss}></View>
          <View className='content' style={`top: ${top}rpx;`}>
            <ScrollView className='main-scroll' scrollY>
              <View className="main-content">
                {
                  list.map((item, index) => {
                    return (
                      <View key={index} className={`cell-item ${item.selected ? 'cell-item_sel' : ''} ${index == list.length - 1 ? '' : 'border-bottom_1px'}`} onClick={this.onCellItemTaped.bind(this, index)}>
                        {item.title}
                      </View>
                    )
                  })
                }
              </View>
            </ScrollView>
          </View>
        </View>
      ) : null
    )
  }

  _handleEvent = e => {
    e.stopPropagation()
  }

  dismiss = () => {
    this.props.onDismiss && this.props.onDismiss()
    this.setState({
      isShow: false
    })
  }

  show = (currentSort: any) => {
    currentSort = currentSort || {}
    const { dataList } = this.props
    let list: any[] = dataList.map(item => {
      return {
        title: item.title,
        code: item.code,
        selected: (currentSort.code || 'SYNTHESIS') == item.code
      }
    })

    this.setState({
      isShow: true,
      list: list
    })
  }

  onCellItemTaped = (index: number) => {
    const { list } = this.state
    this.props.onSelect && this.props.onSelect(list[index])
  }
}
